package com.qclix.inv.textui;

import com.qclix.inv.*;

import java.util.Date;
import java.util.List;

/**
 * Handles new invoice addition
 */
public class NewInvoiceHandler extends AbstractActionHandler {

    private InvoiceService invoiceService;

    public void setInvoiceService(InvoiceService invoiceService) {
        this.invoiceService = invoiceService;
    }
    
    public void handle() {
        Invoice invoice = new Invoice();
        InvoiceLine invoiceLine = new InvoiceLine();
        invoice.setIssueDate(new Date());

        setNextHandler(FlowHandler.HANDLER.topMenu);

        try {
            if (!invoiceService.hasAtLeastOneClient()) {
                System.out.println("There is no client configured. Please start with client creation.");
                return;
            }
        } catch (InvoiceServiceException e) {
            System.out.println("Oops, an error occured while checking if there was at least one client");
            return;
        }

        System.out.println("Fill the product data (only one product per invoice so far):");
        System.out.print("\tDescription: ");
        invoiceLine.setDescription(readValue());
        System.out.print("\tUnit price: ");
        invoiceLine.setUnitPrice(Float.parseFloat(readValue()));
        boolean valueOK = false;
        while (! valueOK) {
            System.out.print("\tQuantity: ");
            try {
                invoiceLine.setQuantity(Integer.parseInt(readValue()));
            } catch (NumberFormatException e) {
                System.out.println("The quantity must be a positive integer value.");
            }
            valueOK = true;
        }
        System.out.print("\tVAT amount (%): (21%) ");
        invoiceLine.setVat(Float.parseFloat(readValue("21")) / 100);
        invoice.getLines().add(invoiceLine);

        System.out.println("Select the client:");

        List<Client> clients = null;
        try {
            clients = invoiceService.getClients();
        } catch (InvoiceServiceException e) {
            System.out.println("Oops, an error occured while fetching clients");
            return;
        }
        if (clients.size() > 0) {
            for (int i = 1; i <= clients.size(); i++) {
                System.out.println("\t(" + i + ") " + clients.get(i-1).getName());
            }
            System.out.print("Select a client: ");
            Client selectedClient = clients.get(Integer.parseInt(readChoice("-1")) - 1);
            invoice.setClient(selectedClient);
            try {
                invoiceService.addInvoice(invoice);
            } catch (InvoiceServiceException e) {
                System.out.println("An error occured while saving the invoice");
                return;
            }
        } else {
            System.out.println("Oops, no clients in database! Please configure the client before.");
        }
    }
    
}
